﻿var maps = new Array();
var directions = new Array();

var findMap = function(id) {
    for (i = 0; i < maps.length; i++) {
        if (maps[i].Id == id)
            return maps[i];
    }
}

var findDirections = function(id) {
    for (i = 0; i < directions.length; i++) {
        if (directions[i].Id == id)
            return directions[i];
    }
}

var createMap = function(id, latitude, longitude, address, zoom, iconUrl, iconWidth, iconHeight, iconAnchorX, iconAnchorY) {
    var map = new GMap2(document.getElementById(id));
    maps[maps.length] = { Id: id, Map: map };
    var geocoder = new GClientGeocoder();
    if (map) {
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

        if (latitude && longitude) {

            setMapLociation(new GLatLng(latitude, longitude), map, zoom, iconUrl, iconWidth, iconHeight, iconAnchorX, iconAnchorY);
        }
        else {
            var geocoder = new GClientGeocoder();
            geocoder.getLatLng(address, function(point) {
                setMapLociation(point, map, zoom, iconUrl, iconWidth, iconHeight, iconAnchorX, iconAnchorY);
            });
        }
    }
}

var setMapLociation = function(thePoint, theMap, zoom, iconUrl, iconWidth, iconHeight, iconAnchorX, iconAnchorY) {
    if (thePoint && theMap) {
        theMap.setCenter(thePoint, zoom);

        if (iconUrl && iconUrl.length > 0) {

            var tmpIcon = new GIcon();
            tmpIcon.image = iconUrl;
            tmpIcon.iconSize = new GSize(iconWidth, iconHeight);
            tmpIcon.iconAnchor = new GPoint(iconAnchorX, iconAnchorY);

            var marker = new GMarker(thePoint, { icon: tmpIcon });
            theMap.addOverlay(marker);
        }
        else {
            var marker = new GMarker(thePoint);
            theMap.addOverlay(marker);
        }

    }
}

var getDirections = function(mapId, txtId, directionsId, dest) {
    var map = findMap(mapId);
    var txt = document.getElementById(txtId);
    var directionObject = findDirections(directionsId);
    if (map && txt && txt.value && txt.value.length > 0) {
        var tmp = null;
        if (directionObject) {
            tmp = directionObject.Directions;
            tmp.clear();
        }
        else {
            var directionsDiv = document.getElementById(directionsId);
            tmp = new GDirections(map.Map, directionsDiv, "en_UK");
            GEvent.addListener(tmp, "error", function(sender) { alert(sender.getStatus().code + ": " + sender.getStatus().request); });
            //tmp.clear();
            directions[directions.length] = { Id: directionsId, Directions: tmp };
        }
        if (tmp) {
            //alert(txt.value + " to " + dest);
            //tmp.load("from: " + txt.value + " to: " + dest);
            tmp.load("from: Bristol to: SP3");
        }
    }
    return false;
}